﻿//函数的声明
#include"snake.h"

/* typedef struct _COORD {
      SHORT X;
      SHORT Y;
 } COORD, *PCOORD
  表??个字符在控制台屏幕幕缓冲区上的坐标 */

void Setpos(short x,short y) {
    //获取句柄
    HANDLE handle = NULL;
    handle = GetStdHandle(STD_OUTPUT_HANDLE);
    //设置光标位置
    COORD pos = { x,y };
    SetConsoleCursorPosition(handle, pos);
}
void My_time() {
    while (1) {
        Setpos(30, 28);
        //printf("你已游戏%.2d 秒,剩余时间为%.2d 秒\n", (int)clock() / 1000,(10-(clock() / 1000)));
        printf("剩余时间%.2d秒\n", (10 - (clock() / 1000)));
        //Sleep(1000);
        if (clock() > 10000) {
            break;
        }
    }
}
void WelcomeToGame() {
    Setpos(40, 15);
    printf("欢迎来到贪吃蛇游戏!\n");
    Setpos(40, 25);    //设置按任意键继续的位置
    system("pause");
    system("cls");
    Setpos(25, 13);
    printf("使用按键“↑↓←→”控制蛇的移动,按F3加速，F4减速\n");
    Setpos(40, 25);   //设置按任意键继续的位置
    system("pause");
    system("cls");
}
void PrintMap() {
    int i = 0;
    //打印上横排
    for (i = 0; i < 58; i+=2) {  //0~56
        Setpos(i, 0);
        wprintf(L"%c",WALL);
    }
    //打印下横排
    for (i = 0; i < 58; i+=2) {  //0~56
        Setpos(i, 26);
        wprintf(L"%c", WALL);
    }
    //打印左竖排
    for (i = 1; i < 26; i++) {
        Setpos(0, i);
        wprintf(L"%c", WALL);
    }
    //打印右竖排
    for (i = 1; i < 26; i++) {
        Setpos(56, i);
        wprintf(L"%c", WALL);
    }
}
//初始化蛇身
void InitSnack(pSnack ps){
    //蛇身初始化五个节点
    int i = 0;
    pSnackNode cur = NULL;
    for (i = 0; i < 5; i++) {
        cur = (pSnackNode)malloc(sizeof(SnackNode));
        if (cur == NULL) {
            perror("malloc cur fail");
            return;
        }
        cur->next = NULL;
        cur->x = SNACK_X + i * 2;
        cur->y = SNACK_Y;

        if (ps->_phead == NULL) {  //空链表
            ps->_phead = cur;
        }
        else {
            //头插法
            cur->next = ps->_phead;
            ps->_phead = cur;
        }
    }
    cur = ps->_phead;
    while (cur) {
        Setpos(cur->x, cur->y);
        wprintf(L"%c",BODY);
        cur = cur->next;
    }
    //设置其他属性
    ps->_dir = RIGHT;
    ps->_foodscore = 20;
    ps->_score = 0;
    ps->_sleep_time = 200;
    ps->_status = OK;
}
//创建食物
void CreateFood(pSnack ps) {
    int x=0, y=0;
again:
    do {
        x = rand() % 53 + 2; //2~54
        y = rand() % 25 + 1;//1~25
    } while (x % 2 != 0);//x必须要是2的倍数

    //x,y坐标不能与蛇身重合
    pSnackNode cur = ps->_phead;
    while (cur) {
        if (cur->x == x && cur->y == y) { 
            goto again;
        }
        cur = cur->next;
    }
    //创建食物节点
    pSnackNode pfood = (pSnackNode)malloc(sizeof(SnackNode));
    if (!pfood) {
        perror("malloc pfood fail");
        return;
    }
    else {
        pfood->x = x;
        pfood->y = y;
        ps->_pfood = pfood;
        Setpos(x, y);
        wprintf(L"%c",FOOD);
    }
}
void GameStart(pSnack ps) {
    
    //设置窗体长和宽
    system("mode con cols=100 lines=30");

    //获取句柄
    HANDLE houtput = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO cursor_info;  

    GetConsoleCursorInfo(houtput, &cursor_info);  //获取控制台光标信息
    cursor_info.bVisible = false;  //设置光标可见度
    SetConsoleCursorInfo(houtput, &cursor_info);   //设置光标
#if 0
    //获取标准输出设备的句柄
    HANDLE houtput = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos = { 10,15 };
    //定义一个光标结构的结构体
    CONSOLE_CURSOR_INFO cursor_info;
    //获取和houtput句柄相关的控制台上的光标信息
    GetConsoleCursorInfo(houtput, &cursor_info);
    //cursor_info.dwSize = 25;
    cursor_info.bVisible = false;
    SetConsoleCursorInfo(houtput, &cursor_info);
    getchar();
#endif
    //1.打印欢迎窗口 
    //2.功能展示
    WelcomeToGame();
    //3.打印地图
    PrintMap();
    //4.创建蛇
    InitSnack(ps);
    //5.创建食物
    CreateFood(ps);
}

void PrintHelpInfo() {
   
    Setpos(62, 14);
    printf("不能撞到墙，不能撞到自己");
    Setpos(62,15);
    printf("使用按键“↑↓←→”控制蛇的移动");
    Setpos(62,16);
    printf("按F3加速，F4减速");
    Setpos(62, 17);
    printf("按空格暂停游戏，按ESC退出游戏");

}
void Pause() {
    while (1) {
        Sleep(200);
        if (KEY_PRESS(VK_SPACE)) {
            break;
        }
    }
}
int NextisFood(pSnackNode psn,pSnack ps) {
    return (psn->x == ps->_pfood->x) && (psn->y == ps->_pfood->y);
}
void EatFood(pSnackNode psn, pSnack ps) {
    //头插法
    psn->next = ps->_phead;
    ps->_phead = psn;
    //加分
    ps->_score += ps->_foodscore;
    //打印蛇身
    pSnackNode cur = ps->_phead;
    while (cur) {
        Setpos(cur->x, cur->y);
        wprintf(L"%lc", BODY);
        cur = cur->next;
    }
    //释放食物节点
    free(ps->_pfood);
    //创建新的⻝物
    CreateFood(ps);
}
void NoFood(pSnackNode psn, pSnack ps){
    psn->next = ps->_phead;
    ps->_phead = psn;
    pSnackNode cur = ps->_phead;
    while (cur->next->next!=NULL) {
        Setpos(cur->x, cur->y);
        wprintf(L"%lc", BODY);
        cur = cur->next;
    }
    //最后一个节点空格覆盖
    Setpos(cur->next->x, cur->next->y);
    printf("  ");
    //释放最后一个节点 并把此时的蛇尾next指针置为空 
    free(cur->next);
    cur->next = NULL;
}
int KillbySelf(pSnack ps) {
    //判断蛇身与蛇头是否重合
    pSnackNode cur = ps->_phead->next;
    while (cur) {
        if (ps->_phead->x == cur->x && ps->_phead->y == cur->y) {   //撞到自己 
            ps->_status = KILL_BY_SELF;
            return 1;
        }
        cur = cur->next;
    }
    return 0;
}
int KillbyWall(pSnack ps) {
    //判断蛇头是否撞墙
    if (ps->_phead->x == 0 || ps->_phead->x == 56 || ps->_phead->y == 0 || ps->_phead->y == 26) {
        ps->_status = KILL_BY_WALL;
        return 1;
     }
    return 0;
}
void SnackMove(pSnack ps) {
    //创建一个新的节点 表示蛇下一步到的位置 
    pSnackNode pNextNode = (pSnackNode)malloc(sizeof( SnackNode));
    if (!pNextNode) {
        perror("SnakeMove()::malloc()");
        return;
    }
    //判断下一步的方向
	switch (ps->_dir) {

	case UP:
        pNextNode->x = ps->_phead->x;
        pNextNode->y = ps->_phead->y - 1;
		break;
	case DOWN:
        pNextNode->x = ps->_phead->x;
        pNextNode->y = ps->_phead->y + 1;
        break;
	case LEFT:
        pNextNode->x = ps->_phead->x - 2;
        pNextNode->y = ps->_phead->y;
        break;
	case RIGHT:
        pNextNode->x = ps->_phead->x + 2;
        pNextNode->y = ps->_phead->y;
        break;
	}
    if (NextisFood(pNextNode,ps)) {
        EatFood(pNextNode, ps);
    }
    else {
        NoFood(pNextNode, ps);
    }
    KillbySelf(ps);
    KillbyWall(ps);

}
void GameRun(pSnack ps) {
    PrintHelpInfo();  //打印右侧帮助信息
    //按键判断
    do {
        Setpos(62, 10);
        printf("总得分：%d",ps->_score);
        Setpos(62, 11);
        printf("一个食物的分数：%d", ps->_foodscore);
        if (KEY_PRESS(VK_UP) && ps->_dir != DOWN) {
            ps->_dir = UP;
        }
        else if (KEY_PRESS(VK_DOWN) && ps->_dir != UP) {
            ps->_dir = DOWN;
        }
        else if (KEY_PRESS(VK_RIGHT) && ps->_dir != LEFT) {
            ps->_dir = RIGHT;
        }
        else if (KEY_PRESS(VK_LEFT) && ps->_dir != RIGHT) {
            ps->_dir = LEFT;
        }
        else if (KEY_PRESS(VK_ESCAPE)) {
            ps->_status = END_NORMAL; //正常退出
            break;
        }
        else if (KEY_PRESS(VK_SPACE)) {
            Pause();  //让页面暂停 再按一次空格恢复
        }
        else if (KEY_PRESS(VK_F3)) {
            //加速
            if (ps->_sleep_time < 320) {
                ps->_sleep_time -= 30;
                ps->_foodscore += 10;
            }
        }
        else if (KEY_PRESS(VK_F4)) {
            //减速
            if (ps->_sleep_time>=80) {
                ps->_sleep_time += 30;
                ps->_foodscore -= 10;
            }
        }
        SnackMove(ps);
        Sleep(ps->_sleep_time);

    } while (ps->_status==OK);
}
void GameOver(pSnack ps) {
    pSnackNode cur = ps->_phead;
    Setpos(30, 12);
    switch (ps->_status)
    {
    case END_NORMAL:
        printf("您主动退出游戏\n");
        break;
    case KILL_BY_SELF:
        printf("您撞上自己了 ,游戏结束!\n");
        break;
    case KILL_BY_WALL:
        printf("您撞墙了,游戏结束!\n");
        break;
    } 
    //释放蛇身的节点
    while (cur)
    {
        pSnackNode del = cur;
        cur = cur->next;
        free(del);
    }

}